package com.flyqiu.flow.core.deploy;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.flyqiu.common.bean.FlyQiuBeanManage;
import com.flyqiu.common.user.FlyQiuUserTools;
import com.flyqiu.flow.api.context.FlyQiuFlowGlobalContext;
import com.flyqiu.flow.api.deploy.IFlowDeploy;
import com.flyqiu.flow.common.enums.ProcDeployType;
import com.flyqiu.flow.mapper.ProcDeploySourceMapper;
import com.flyqiu.flow.model.entity.ProcDeployDef;
import com.flyqiu.flow.model.entity.ProcDeploySource;

/**
 * 手动流程发布
 */
public class ManualProcDeploy implements IFlowDeploy {
    private final ProcDeploySourceMapper procDeploySourceMapper;

    public ManualProcDeploy(FlyQiuFlowGlobalContext globalContext) {
        FlyQiuBeanManage procBean = globalContext.getBeanManage();
        this.procDeploySourceMapper = procBean.getMapper(ProcDeploySourceMapper.class);
    }

    @Override
    public ProcDeploySource deploy(JSONObject modelSource, String procDefKey, String procName, String category) {
        LambdaQueryWrapper<ProcDeploySource> procDeployWrapper = new LambdaQueryWrapper<>();
        procDeployWrapper.eq(ProcDeploySource::getDeployModelKey, procDefKey);
        ProcDeploySource procDeploySource = procDeploySourceMapper.selectOne(procDeployWrapper);
        if (procDeploySource == null) {
            procDeploySource = new ProcDeploySource();
            procDeploySource.setDeploySourceVersion(0);
        }
        procDeploySource.setDeploySource(modelSource);
        procDeploySource.setDeployModelKey(procDefKey);
        procDeploySource.setTenantId(FlyQiuUserTools.getTenantId());
        procDeploySource.setDeploySourceVersion(procDeploySource.getDeploySourceVersion() + 1);
        if (StringUtils.checkValNull(procDeploySource.getId())) {
            procDeploySourceMapper.insert(procDeploySource);
        } else {
            procDeploySourceMapper.updateById(procDeploySource);
        }

        return procDeploySource;
    }

    @Override
    public void deleteDeploy(ProcDeployDef procDeployDef) {
        procDeploySourceMapper.deleteById(procDeployDef.getDeploySourceId());
    }

    /**
     * 根据发布id
     *
     * @param deploySourceId
     * @return
     */
    @Override
    public JSONObject getModelSource(String deploySourceId) {
        ProcDeploySource procDeploySource = procDeploySourceMapper.selectById(deploySourceId);
        return procDeploySource.getDeploySource();
    }

    /**
     * 流程部署唯一标识
     *
     * @return
     */
    @Override
    public String procDeployKey() {
        return ProcDeployType.MANUAL.getValue();
    }

    /**
     * 流程部署器名称
     *
     * @return
     */
    @Override
    public String procDeployName() {
        return ProcDeployType.MANUAL.getLabel();
    }
}
